<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/2/26
 * Time: 下午2:37
 */
class Pay extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->library('session');
        $this->load->model('bill_model');
        $this->load->model('customer_model');
    }

    // 账期还款
    public function index()
    {
        if (isset($_GET['bn'])) {
            $bill_bn = $_GET['bn'];
            $where = array('bill_bn' => $bill_bn);
            $data = $this->db->where($where)->from('app_bill')->get()->row_array();
            if (!$data) {
                exit('没有要还款的账单');
            }
            if($data['status'] == 1){
                 exit('账单已还款');
            }
        } else {
            $customer_id = $this->session->customer_id;
            if ($customer_id) {
                $all_customer_id = $this->customer_model->get_customer_user($customer_id);
                $this->db->where('status=', 0);
                $this->db->where('start_repayment_date!=', NULL);
                $this->db->where_in('customer_id', $all_customer_id);
                $data = $this->db->from('app_bill')->order_by('should_repayment_date', 'asc')->limit(1)->get()->row_array();
                if (!$data) {
                    exit('没有要还款的账单');
                }
            } else {
                exit('请先登录');
            }
        }
        $data['customer_info'] = $this->db->where(array('id'=>$data['customer_id']))->from('app_customer')->get()->row_array();

        // $where = array(
        //     'bill_id' => $data['id']
        // );

        $data['bill_id'] = $data['id'];
        $data['bill_approve'] = $this->getTree($data['id'],0);

       // $data['bill_approve'] = $this->db->where($where)->from('app_bill_approve')->order_by('id','desc')->get()->result_array();
        if(isset($_GET['id']) && $_GET['id'] != ""){
            $data['pre_id'] = $_GET['id'];
        }else{
            $data['pre_id'] = "";
        }

        //人民币网关账号，该账号为11位人民币网关商户编号+01,该参数必填。
        $data['merchantAcctId'] = "1001213884201";
        //编码方式，1代表 UTF-8; 2 代表 GBK; 3代表 GB2312 默认为1,该参数必填。
        $data['inputCharset'] = "1";
        //接收支付结果的页面地址，该参数一般置为空即可。
        $data['pageUrl'] = "";
        //服务器接收支付结果的后台地址，该参数务必填写，不能为空。
        $data['bgUrl'] = base_url() . "rmb/recieve.php";
        //网关版本，固定值：v2.0,该参数必填。
        $data['version'] = "v2.0";
        //语言种类，1代表中文显示，2代表英文显示。默认为1,该参数必填。
        $data['language'] = "1";
        //签名类型,该值为4，代表PKI加密方式,该参数必填。
        $data['signType'] = "4";
        //支付人姓名,可以为空。
        $data['payerName'] = "";
        //支付人联系类型，1 代表电子邮件方式；2 代表手机联系方式。可以为空。
        $data['payerContactType'] = "1";
        //支付人联系方式，与payerContactType设置对应，payerContactType为1，则填写邮箱地址；payerContactType为2，则填写手机号码。可以为空。
        $data['payerContact'] = "1210320095@qq.com";
        //商户订单号，以下采用时间来定义订单号，商户可以根据自己订单号的定义规则来定义该值，不能为空。
        $data['orderId'] = $data['bill_bn'];
        //订单金额，金额以“分”为单位，商户测试以1分测试即可，切勿以大金额测试。该参数必填。
        $data['orderAmount'] = "1";
        //订单提交时间，格式：yyyyMMddHHmmss，如：20071117020101，不能为空。
        $data['orderTime'] = date("YmdHis");
        //商品名称，可以为空。
        $data['productName'] = "文具一号账期还款";
        //商品数量，可以为空。
        $data['productNum'] = "";
        //商品代码，可以为空。
        $data['productId'] = "";
        //商品描述，可以为空。
        $data['productDesc'] = "";
        //扩展字段1，商户可以传递自己需要的参数，支付完快钱会原值返回，可以为空。
        $data['ext1'] = "";
        //扩展自段2，商户可以传递自己需要的参数，支付完快钱会原值返回，可以为空。
        $data['ext2'] = "";
        //支付方式，一般为00，代表所有的支付方式。如果是银行直连商户，该值为10，必填。
        $data['payType'] = "10";
        //银行代码，如果payType为00，该值可以为空；如果payType为10，该值必须填写，具体请参考银行列表。
        $data['bankId'] = "";
        //同一订单禁止重复提交标志，实物购物车填1，虚拟产品用0。1代表只能提交一次，0代表在支付不成功情况下可以再提交。可为空。
        $data['redoFlag'] = "";
        //快钱合作伙伴的帐户号，即商户编号，可为空。
        $data['pid'] = "";
        // signMsg 签名字符串 不可空，生成加密签名串
        $this->load->view('pay/index', $data);
    }

    //获取下级审批信息
    public function getTree($id, $pid = 0)
    {


        $where = array(
            'bill_id' => $id,
            'prev_id' => $pid
        );

        $list = $this->db->where($where)->from('app_bill_approve')->order_by('id','desc')->get()->result_array();
        if (!$list || count($list) == 0) {
            return false;
        }
  
        foreach ($list as $k => $v) {
            $list[$k]['child'] = $this->getTree($v['bill_id'],$v['id']);
        }

        return $list;
    }

    //获取签名
    public function sign()
    {
        $post = $this->input->post();
        $kq_all_para = $this->kq_ck_null($post['inputCharset'], 'inputCharset');
        $kq_all_para .= $this->kq_ck_null($post['pageUrl'], "pageUrl");
        $kq_all_para .= $this->kq_ck_null($post['bgUrl'], 'bgUrl');
        $kq_all_para .= $this->kq_ck_null($post['version'], 'version');
        $kq_all_para .= $this->kq_ck_null($post['language'], 'language');
        $kq_all_para .= $this->kq_ck_null($post['signType'], 'signType');
        $kq_all_para .= $this->kq_ck_null($post['merchantAcctId'], 'merchantAcctId');
        $kq_all_para .= $this->kq_ck_null($post['payerName'], 'payerName');
        $kq_all_para .= $this->kq_ck_null($post['payerContactType'], 'payerContactType');
        $kq_all_para .= $this->kq_ck_null($post['payerContact'], 'payerContact');
        $kq_all_para .= $this->kq_ck_null($post['orderId'], 'orderId');
        $kq_all_para .= $this->kq_ck_null($post['orderAmount'], 'orderAmount');
        $kq_all_para .= $this->kq_ck_null($post['orderTime'], 'orderTime');
        $kq_all_para .= $this->kq_ck_null($post['productName'], 'productName');
        $kq_all_para .= $this->kq_ck_null($post['productNum'], 'productNum');
        $kq_all_para .= $this->kq_ck_null($post['productId'], 'productId');
        $kq_all_para .= $this->kq_ck_null($post['productDesc'], 'productDesc');
        $kq_all_para .= $this->kq_ck_null($post['ext1'], 'ext1');
        $kq_all_para .= $this->kq_ck_null($post['ext2'], 'ext2');
        $kq_all_para .= $this->kq_ck_null($post['payType'], 'payType');
        $kq_all_para .= $this->kq_ck_null($post['bankId'], 'bankId');
        $kq_all_para .= $this->kq_ck_null($post['redoFlag'], 'redoFlag');
        $kq_all_para .= $this->kq_ck_null($post['pid'], 'pid');
        $kq_all_para = substr($kq_all_para, 0, strlen($kq_all_para) - 1);
        /////////////  RSA 签名计算 ///////// 开始 //

        $fp = fopen(base_url() . "rmb/99bill-rsa.pem", "r");
        $priv_key = fread($fp, 123456);
        fclose($fp);
        $pkeyid = openssl_get_privatekey($priv_key);
        // compute signature
        openssl_sign($kq_all_para, $signMsg, $pkeyid, OPENSSL_ALGO_SHA1);

        // free the key from memory
        openssl_free_key($pkeyid);

        $signMsg = base64_encode($signMsg);
        /////////////  RSA 签名计算 ///////// 结束 //
        if ($signMsg) {
            send_json(array('code' => 0, 'data' => $signMsg, 'msg' => ''));
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => '签名错误'));
        }

    }

    //获取签名字符串
    public function kq_ck_null($kq_va, $kq_na)
    {
        if ($kq_va == "") {
            $kq_va = "";
        } else {
            return $kq_va = $kq_na . '=' . $kq_va . '&';
        }
    }

    //快钱支付成功，展示页面
    public function show()
    {
        $bill_bn = $_GET['orderId'];
        $where = array('bill_bn' => $bill_bn);
        $this->db->where($where)->update('app_bill', array('status' => 1,'actual_repayment_date'=>date("Y-m-d H:i:s",time())));
        $bill = $this->db->where($where)->select('customer_id,id,money')->from('app_bill')->get()->row_array();
        //获取admin的id;
        $admin_id = $this->customer_model->get_admin_customer_id($bill['customer_id']);
        $where = array('customer_id' => $admin_id);
        $this->db->where(array('customer_id'=>$admin_id));
        $this->db->set('account_period_quota_used',"account_period_quota_used -'".$bill['money']."'",FALSE);
        $result = $this->db->update('app_admin');
        if($result){
            $where = array('customer_id' => $admin_id);
            $user = $this->db->where($where)->select('customer_id,account_period_pay_status,account_period_type,account_period_quota,account_period_quota_used')->from('app_admin')->get()->row_array();
            $left_quato = $user['account_period_quota'] - $user['account_period_quota_used'];
            $message_history['receiver_customer_id'] = $user['customer_id'];
            $message_history['send_customer_id'] = 0;
            $message_history['title'] = '账期还款';
            $message_history['content'] = '尊敬的客户，您的账期额度已恢复至￥'.$left_quato.'元，可以继续采购哦~';
            $message_history['read_status'] = 0;
            $message_history['created_at'] = date("Y-m-d H:i:s",time());
            $result = $this->db->insert('message_history',$message_history);

            if ($user['account_period_pay_status'] == 0) {
                $res = $this->db->where($where)->update('app_admin', array('account_period_pay_status' => 1));
                if ($res) {
                    $data['customer_id'] = $admin_id;
                    $data['type'] = 3;
                    $data['reason'] = '已还款';
                    $data['bill_id'] = $bill['id'];
                    $data['operator_id'] = 1;
                    $data['created_at'] = date("Y-m-d H:i:s", time());
                    $this->db->insert('app_account_period_open_close_record', $data);
                }
            }
        }
        
        $data['account_period_type'] = $user['account_period_type'];
        $this->load->view('pay/show', $data);
    }

    //发送邮件
    public function send_email()
    {
        $post = $this->input->post();
        $bill_bn = $post['bill_bn'];
        $where = array('bill_bn' => $bill_bn);
        $field = '*,
                    (select name from app_customer where app_customer.id = app_bill.customer_id) as customer_name,
                    (select company from app_customer where app_customer.id = app_bill.customer_id) as customer_company,
                    (select tel from app_customer where app_customer.id = app_bill.customer_id) as customer_tel,
                    (select invoice_bn from app_bill_invoice where app_bill_invoice.bill_id = app_bill.id) as bill_invoice_bn,
                    (select invoice_title from app_bill_invoice where app_bill_invoice.bill_id = app_bill.id) as bill_invoice_title,
                    (select id from app_bill_invoice where app_bill_invoice.bill_id = app_bill.id) as bill_invoice_id,
                    (select invoice_money from app_bill_invoice where app_bill_invoice.bill_id = app_bill.id) as bill_invoice_money,
                    (select created_at from app_bill_invoice where app_bill_invoice.bill_id = app_bill.id) as bill_invoice_created_at';
        $data = $this->db->where($where)->select($field)->from('app_bill')->get()->row_array();
        $where = array('a.bill_id' => $data['id']);
        $bill_invoice_order = $this->db->where($where)->select('b.*,c.name as customer_name,d.name as cost_center_name,c.username as customer_username,c.tel as customer_tel')->from('app_order_bill a')
            ->join('app_order b', 'b.id=a.order_id')
            ->join('app_customer c', 'c.id=b.customer_id')
            ->join('app_cost_center d', 'd.customer_id=b.customer_id')
            ->get()->result_array();

        $rowspan = count($bill_invoice_order) + 1;
        $where = array(
            'bill_id' => $data['id']
        );
        //内容保存数据库 以便读取
       // $ls = $this->db->where($where)->from('app_bill_approve')->order_by("id", "desc")->get()->row_array();
        if (isset($post['id']) && $post['id'] != "") {
            $rowarr['prev_id'] = $post['id'];
        } else {
            $rowarr['prev_id'] = 0;
        }
        $rowarr['bill_id'] = $data['id'];
        $rowarr['name'] = $post['name'];
        $rowarr['email'] = $post['email'];
        $rowarr['remark'] = $post['remark'];
        $rowarr['created_at'] = date('Y-m-d H:i:s', time());
        $this->db->insert('app_bill_approve', $rowarr);
        $ls_id = $this->db->insert_id();

        //获取所有发送审批信息
        $lss = $this->db->where($where)->from('app_bill_approve')->get()->result_array();
        $lss_count = count($lss);
        if (!$data) {
            exit('账单不存在');
        }
        $content1 = '
  <style type="text/css">

.right-border .account-moeny .pay:hover {
  text-decoration: none;
}

.left-border .approve .approve-next:hover {
  cursor: pointer;
  text-decoration: none;
}


</style>
<div style="background-color: #fff;width: 100%;height: 1200px;margin-left: auto;margin-right: auto;">
  <div style="margin-left: 50px;margin-right: 20px;padding-top: 20px;">
    <div style="float: left;display: inline;width: 130px;overflow: hidden;">
        <a title="文具1号—办公用品采购网站 阳光价格 老板放心 品质保障 员工省力">
            <img alt="文具1号—办公用品采购网站 阳光价格 老板放心 品质保障 员工省力" src="' . base_url() . 'public/images/logo.jpg" width="130" height="55">
        </a>
    </div>
    <div style="float: right;">
    <p style="bold;margin-left: 20px;margin-top: 0px;">账期账单支付</p>
    <p style="bold;margin-left: 20px;margin-top: -10px;">4008-215-248</p>
    </div>
  </div>
   <div style="border-top:1px solid #DCDCDC;margin-top: 60px;width: 100%;margin-left: 50px;margin-right:20px;"></div>
   <div>
     <div style="margin-top: 10px;border:1px solid #DCDCDC;height: 250px;width: 35%;margin-left: 50px;float: left;overflow-y:scroll;">
      <h2 style="margin-left: 20px;margin-top: 20px;font-size: 17px;font-weight: bold;">审批流</h2>';
        $content2 = "";
        foreach ($lss as $key => $value) {
            if ($key == 0) {
                $content2 .= '<div style="padding-bottom: 2px;margin-left: 25px;">
        收件人：<span style="font-weight: bold;">' . $value['created_at'] . ' ' . $value['name'] . '---' . $value['email'] . '</span><br>
        <span style="border-left:1px solid #DCDCDC;margin-left: 15px;line-height: 30px;"></span><span style="margin-left: 30px;">(' . $value['remark'] . ')</span>
       </div>';
            } else if ($key > 0 && ($key + 1) < $lss_count) {
                $content2 .= '
       <div style="padding-bottom: 2px;margin-left: 25px;">收件人：<span style="font-weight: bold;">' . $value['created_at'] . ' ' . $value['name'] . '---' . $value['email'] . '</span> <br>
        <span style="border-left:1px solid #DCDCDC;margin-left: 15px;line-height: 30px;"></span><span style="margin-left: 30px;">(' . $value['remark'] . ')</span>
       </div>';

            } else if (($key + 1) == $lss_count) {
                $content2 .= '<div style="padding-bottom: 2px;margin-left: 25px;">收件人：<span style="font-weight: bold;">' . $value['created_at'] . ' ' . $value['name'] . '---' . $value['email'] . '</span></div>';
            }

        }
        $content3 = '<div style="margin-top: 20px;margin-bottom: 20px;margin-left: 120px;background-color: #DC143C;border: none;color: white;padding: 2px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 13px;border-radius: 3px;">
        <a style="color: white;text-decoration: none;" href="' . base_url() . 'pay/index?bn=' . $data['bill_bn'] . '&id='.$ls_id.'">提交至下一位审批者</a>
        </div>
     </div>
     <div style="margin-top: 10px;border:1px solid #DCDCDC;height: 250px;width: 55%;margin-right:50px;float: right;">
       <h2 style="margin-left: 20px;margin-top: 20px;font-size: 17px;font-weight: bold;">尊敬的上海信息科技有限公司:</h2>
       <p style="margin-left: 20px;margin-top: 20px;">
        这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。这里是简单的内容。
       </p>
       <div style="text-align: center;margin-top: 20px;">
       <span style="font-size: 20px;">账单金额：</span>
       <span style="font-size: 20px;color: #DC143C;">￥' . $data['money'] . '</span>
       <a style="font-size: 20px;color: #4169E1;padding: 0 10px;cursor: pointer;" href="' . base_url() . 'pay/index?bn=' . $data['bill_bn'] . '&id='.$ls_id.'">确认支付>></a>
        </div>
     </div>
   </div>';
        if ($data['type'] == 1) {
            $content4 = '<div style="border-top:1px solid #DCDCDC;margin-top: 280px;width: 100%;margin-left: 50px;margin-right:20px;"></div><div style="height: 100px;margin-bottom: 10px;margin-left: 50px;">
      <ul style="height: 30%;margin-top: 10px;">
          <li style="float: left;margin-right: 5%;list-style:none"><b>帐单号：</b>' . $data['bill_bn'] . '</li>
          <li style="float: left;margin-right: 5%;list-style:none"><b>账单周期：</b>' . $data['start_repayment_date'] . '~' . $data['should_repayment_date'] . '</li>
          <li style="float: left;margin-right: 5%;list-style:none"><b>最终还款日：</b>' . $data['actual_repayment_date'] . '</li>
          <li style="float: left;margin-right: 5%;list-style:none"><b>账单总额：</b>' . $data['money'] . '</li>
      </ul>
      <ul style="height: 30%;margin-top: 10px;">
          <li style="float: left;margin-right: 5%;list-style:none"><b>公司名称：</b>' . $data['customer_company'] . '</li>
      </ul>
      <ul style="height: 30%;margin-top: 10px;">
          <li style="float: left;margin-right: 5%;list-style:none"><b>客户姓名：</b>' . $data['customer_name'] . '</li>
          <li style="float: left;margin-right: 5%;list-style:none"><b>联系方式：</b>' . $data['customer_tel'] . '</li>
      </ul>
  </div>
<div style="float: left;margin-bottom:10%;margin-left: 50px;">
    <table border="1" cellspacing="1" cellpadding="0" width="100%">
        <tr>
            <td><b>序号</b></td>
            <td><b>发票编码</b></td>
            <td><b>发票抬头</b></td>
            <td><b>发票金额</b></td>
            <td><b>开票时间</b></td>
            <td><b>订单号</b></td>
            <td><b>订单金额</b></td>
            <td><b>下单账号</b></td>
            <td><b>成本中心</b></td>
            <td><b>联系人</b></td>
            <td><b>联系方式</b></td>
            <td><b>支付时间</b></td>
        </tr>
         <tr>
            <td></td>
            <td rowspan=' . $rowspan . '>' . $data['bill_invoice_bn'] . '</td>
            <td rowspan=' . $rowspan . '>' . $data['bill_invoice_title'] . '</td>
            <td rowspan=' . $rowspan . '>' . $data['bill_invoice_money'] . '</td>
            <td rowspan=' . $rowspan . '>' . $data['bill_invoice_created_at'] . '</td>
        </tr>';
            $content5 = "";
            foreach ($bill_invoice_order as $key => $value) {
                $key = $key + 1;
                $content5 .= '
            <tr>
                <td>' . $key . '</td>
                <td>' . $value['order_bn'] . '</td>
                <td>' . $value['money'] . '</td>
                <td>' . $value['customer_name'] . '</td>
                <td>' . $value['customer_username'] . '</td>
                <td>' . $value['cost_center_name'] . '</td>
                <td>' . $value['customer_tel'] . '</td>
                <td>' . $value['payment_at'] . ' </td>
            </tr>';
            }

            $content6 = '</table></div>';
        } else {
            $content4 = "";
            $content5 = "";
            $content6 = "";
        }
        $content7 = '<div style="border-top:1px solid #DCDCDC;margin-top: 275px;width: 100%;margin-left: 50px;margin-right:20px;"></div>
    <div style="margin-left: 50px;margin-right: 20px;padding-top: 20px;">
    <div style="float: left;display: inline;width: 130px;overflow: hidden;">
        <a title="文具1号—办公用品采购网站 阳光价格 老板放心 品质保障 员工省力">
            <img alt="文具1号—办公用品采购网站 阳光价格 老板放心 品质保障 员工省力" src="' . base_url() . 'public/images/card_entrance.gif" width="130" height="55">
        </a>
    </div>
    <div style="float: right;">
    <p style="bold;margin-left: 20px;margin-top: -10px;">' . $data['created_at'] . '</p>
    </div>
  </div></div>';


        $content = $content1 . $content2 . $content3 . $content4 . $content5 . $content6 . $content7;
        if (!empty($post['email'])) {
            $sender_name = ''; //发邮件人的地址
            $code = ''; //验证码
            $to_email = $post['email']; //收件人 email 地址
            $title = "账期还款申请"; // email 主题:
            $content = $content;
            $res = $this->bill_model->send_email($sender_name, $to_email, $title, $content, $mailtype = 'html'); //发送email
            if ($res) {
                send_json(array('code' => 0, 'data' => '', 'msg' => '发送成功'));
            } else {
                $where = array(
                    'id' => $ls_id
                );
                $this->db->where($where)->delete('app_bill_approve');
                send_json(array('code' => -1, 'data' => '', 'msg' => '发送失败'));
            }
        }
    }

}
